/*****************************************************************************
* Keppe Messenger (KMP) Keppe Project-Team User Messaging System
* Copyright (C) 2013-2014 Keppe Project-Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

#include "frmConfig.h"
#include "ui_frmConfig.h"
#include <QStyleFactory>
#include <QTranslator>
#include <QFontDialog>
#include <QSettings>
#include <QProcess>
#include <QFont>
#include <QDir>

frmConfig::frmConfig(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::frmConfig)
{
    setWindowFlags(windowFlags()^Qt::WindowContextHelpButtonHint);
    ui->setupUi(this);
#ifdef MACX
    this->setMinimumSize(375,440);
    this->setMaximumSize(375,440);
    this->resize(375,440);
#else
#ifdef UNIX
    this->setMinimumSize(350,440);
    this->setMaximumSize(350,440);
    this->resize(350,440);
#endif
#endif
    QSettings settings("Keppe","Keppe Messenger");

    //// Interface
    // Font
    settings.beginGroup("Interface");
    bool designedMode = settings.value("designedMode",true).toBool();
    bool classicMode = false;
    if (!designedMode)
    {
        classicMode = true;
    }
    ui->cbClassic->setChecked(classicMode);
    QString currentFontString = settings.value("Font","").toString();
    if (currentFontString != "")
    {
        resetFont = false;
    }
    else
    {
        resetFont = true;
    }
    currentFont.fromString(currentFontString);

    if (!resetFont)
    {
        ui->labPreviewFont->setFont(currentFont);
    }
    else
    {
        QFont systemFont;
        ui->labPreviewFont->setFont(systemFont);
    }

    // Language
    langWrapper["System"] = "System (System)";
    langWrapper["System (System)"] = "System";
    langWrapper["English (English)"] = "en";
    langWrapper["en"] = "English (English)";
    QDir trDir;
    trDir.cd(":/tr");
    foreach(const QString& key, trDir.entryList(putStringToStringList("*.qm")))
    {
        QTranslator trFile;
        bool ok = trFile.load(QString(":/tr/" + key));
        if (ok)
        {
            QString trName = key;
            trName = trName.remove("qt_").remove(".qm");
            QLocale trLocale(trName);
            QString trNative = trLocale.nativeLanguageName();
            QString trInter = QLocale::languageToString(trLocale.language());
            if (trNative != "")
            {
                langWrapper[trName] = trNative + " (" + trInter + ")";
                langWrapper[trNative + " (" + trInter + ")"] = trName;
                if (QFile::exists(QString(":/tr/" + trName + ".png")))
                {
                    ui->cbLanguage->addItem(QIcon::fromTheme("flag-" + trName,QIcon(":/tr/" + trName + ".png")),trNative + " (" + trInter + ")");
                }
                else
                {
                    ui->cbLanguage->addItem(QIcon::fromTheme("flag-" + trName),trNative + " (" + trInter + ")");
                }
            }
        }
    }
    QString langVar = settings.value("Language","System").toString();
    if (langWrapper.contains(langVar))
    {
        QString langName = langWrapper[langVar];
        ui->cbLanguage->setCurrentIndex(ui->cbLanguage->findText(langName));
    }
    settings.endGroup();
    //// Interface

    // Style
    ui->cbStyle->addItems(QStyleFactory::keys());
    QStringList styles;
    styles << "System" << QStyleFactory::keys();
    settings.beginGroup("Style");
    bool loadCustom = settings.value("Custom",false).toBool();
    if (loadCustom)
    {
        QString style = settings.value("Name","System").toString();
        if (style != "System")
        {
            if (style.trimmed() != "")
            {
                if (styles.contains(style))
                {
                    ui->cbStyle->setCurrentIndex(ui->cbStyle->findText(style));
                }
            }
        }
    }
    settings.endGroup();
}

frmConfig::~frmConfig()
{
    delete ui;
}

void frmConfig::on_cmdChangeFont_clicked()
{
    QFont newFont;
    bool ok;
    newFont = QFontDialog::getFont(&ok,currentFont,this,QApplication::tr("Set Font"));
    if (ok)
    {
        currentFont = newFont;
        ui->labPreviewFont->setFont(currentFont);
        resetFont = false;
    }
}

void frmConfig::on_cmdFontReset_clicked()
{
    QFont systemFont;
    currentFont = systemFont;
    ui->labPreviewFont->setFont(currentFont);
    resetFont = true;
}

void frmConfig::on_cmdCancel_clicked()
{
    this->close();
}

void frmConfig::on_cmdOK_clicked()
{
    QSettings settings("Keppe","Keppe Messenger");

    //// Interface
    // Font
    settings.beginGroup("Interface");
    bool classicMode = ui->cbClassic->isChecked();
    bool designedMode = true;
    if (classicMode)
    {
        designedMode = false;
    }
    settings.setValue("designedMode",designedMode);
    if (resetFont)
    {
        settings.remove("Font");
    }
    else
    {
        settings.setValue("Font",currentFont.toString());
    }

    // Language
    QString oldLang = settings.value("Language","System").toString();
    QString newLang = langWrapper[ui->cbLanguage->currentText()];
    if (oldLang != newLang)
    {
        settings.setValue("Language",newLang);
        QProcess *newMessenger = new QProcess;
        newMessenger->startDetached("\"" + qApp->applicationFilePath() + "\"");
        newMessenger->deleteLater();
        qApp->exit(0);
    }
    settings.endGroup();

    //// Interface

    // Style
    settings.beginGroup("Style");
    if (ui->cbStyle->currentIndex() == 0)
    {
        settings.setValue("Custom",false);
    }
    else
    {
        QString newStyle = ui->cbStyle->currentText();
        settings.setValue("Custom",true);
        settings.setValue("showBug",true);
        settings.setValue("Name",newStyle);
        qApp->setStyle(newStyle);
    }
    settings.endGroup();

    this->close();
}

QStringList frmConfig::putStringToStringList(QString string)
{
    QStringList strlist;
    strlist << string;
    return strlist;
}

void frmConfig::on_bbOptions_clicked(QAbstractButton *button)
{
    if (ui->bbOptions->buttonRole(button) == QDialogButtonBox::AcceptRole)
    {
        on_cmdOK_clicked();
    }
    else if (ui->bbOptions->buttonRole(button) == QDialogButtonBox::RejectRole)
    {
        on_cmdCancel_clicked();
    }
}
